<?php
/**
 * Created by PhpStorm.
 * User: J.H
 * Date: 2017/2/28
 * Time: 1:34
 */

namespace lib\oauth\qq;


use lib\curl\HttpRequest;
use lib\oauth\OauthBase;

class QqConnect extends OauthBase
{
    private $url_api = 'https://graph.qq.com/';
    private $app_id;
    private $app_key;
    private $app_callback;
    private $api_scope = 'get_user_info';
    protected $access_token;
    protected $openid;

    function __construct($config = array('appId' => '', 'appKey' => '', 'callback' => ''))
    {
        parent::__construct();
        $this->app_id = $config['appId'];
        $this->app_key = $config['appKey'];
        $this->app_callback = $config['callback'];
    }

    /**
     * @param $scope
     * get_user_info,list_album,upload_pic,do_like 多个API授权逗号隔开
     *
     * @link http://wiki.connect.qq.com/api%E5%88%97%E8%A1%A8
     * @return $this
     */
    function setScope($scope)
    {
        $this->api_scope = $scope;
        return $this;
    }

    /**
     * QQ用户授权登录
     */
    function login()
    {
        $state = $this->setState('qc');
        $params = array(
            'response_type' => 'code',
            'client_id' => $this->app_id,
            'redirect_uri' => $this->app_callback,
            'state' => $state,
            'scope' => $this->api_scope
        );
        $login_url = $this->parseUrl($this->url_api, 'oauth2.0/authorize', $params);
        $this->to($login_url);
    }

    /**
     * @return string
     */
    private function getAccessToken()
    {
        if ($this->access_token) {
            return $this->access_token;
        }
        $state = $this->getState('qc');
        if (isset($_GET['state']) && $_GET['state'] !== $state) {
            $this->error(0);
        }
        if (!isset($_GET['code'])) {
            $this->error(1);
        }
        $params = array(
            'grant_type' => 'authorization_code',
            'client_id' => $this->app_id,
            'client_secret' => $this->app_key,
            'redirect_uri' => $this->app_callback,
            'code' => $_GET['code']
        );
        $access_token_url = $this->parseUrl($this->url_api, 'oauth2.0/token', $params);
        $result = HttpRequest::get($access_token_url);
        parse_str($result, $token);
        if (isset($token['access_token'])) {
            return $this->access_token = $token['access_token'];
        }
        return '';
    }

    /**
     * @return string
     */
    function getOpenid()
    {
        if ($this->openid) {
            return $this->openid;
        }
        if (empty($_GET['code']) && empty($_GET['state'])) {
            $this->login();
        }
        $openid_url = $this->parseUrl($this->url_api, 'oauth2.0/me', array('access_token' => $this->getAccessToken()));
        $result = HttpRequest::get($openid_url);
        if (strpos($result, "callback") !== false) {
            $l = strpos($result, "(");
            $r = strrpos($result, ")");
            $result = substr($result, $l + 1, $r - $l - 1);
        }
        if ($user = json_decode($result, true)) {
            if (!empty($user['openid'])) {
                return $this->openid = $user['openid'];
            }
        }
        return '';
    }

    /**
     * @return array
     * @link http://wiki.connect.qq.com/get_user_info
     */
    function getUserInfo()
    {
        $params = array(
            'openid' => $this->getOpenid(),
            'access_token' => $this->getAccessToken(),
            'oauth_consumer_key' => $this->app_id
        );
        $api = $this->parseUrl($this->url_api, 'user/get_user_info', $params);
        $result = HttpRequest::get($api);
        if (!$user_info = json_decode($result, true)) {
            return array();
        }
        return $user_info;
    }
}